package com.lg.erp.controller.yqy;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lg.erp.entity.JsonResult;
import com.lg.erp.entity.SUser;
import com.lg.erp.entity.yqy.TCategories;
import com.lg.erp.mapper.UserMapper;
import com.lg.erp.service.yqy.ITCategoriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lg
 * @since 2021-04-21
 */
@RestController
public class TCategoriesController {

    @Autowired
    private ITCategoriesService categoriesService;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("allCategories")
    public JsonResult findAllCategories(){
        List<TCategories> list = categoriesService.findAllCategories();
        return new JsonResult(1,"ok",list);
    }

    @RequestMapping("categories")
    public JsonResult selectCategories(){
        List<TCategories> list = categoriesService.list();
        return new JsonResult(1,"ok",list);
    }

    @PostMapping("categories")
    public JsonResult addCategories(@RequestBody TCategories categories){
        categories.setId(UUID.randomUUID().toString().substring(0,15).replace("-",""));
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = (User) principal;
        SUser suser = userMapper.selectOne(new QueryWrapper<SUser>().lambda().eq(SUser::getUsername, user.getUsername()));
        categories.setUserId(suser.getId());
        categoriesService.save(categories);
        return new JsonResult(1,"ok",categories);
    }

    @PutMapping("categories")
    public JsonResult updateCategories(@RequestBody TCategories categories){
        categoriesService.updateById(categories);
        return new JsonResult(1,"ok",null);
    }

    @DeleteMapping("categories/{id}")
    public JsonResult deleteCategories(@PathVariable String id){
        //boolean b = categoriesService.removeById(id);
        boolean b = categoriesService.remove(new QueryWrapper<TCategories>().lambda()
                .eq(TCategories::getId, id));
        return new JsonResult(1,"ok",b);
    }
}
